package org.ithang.lock;

import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 基于mysql实现分布式锁
 * @author Administrator
 *
 */
public class MySQLLockTest {

	private int count=100;
	private BasicDataSource ds=null;
	
	private MySQLLock lock=null;
	@Before
	public void init(){
		try {
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		ds=new BasicDataSource();
		ds.setUrl("jdbc:mysql://127.0.0.1:3306/test?useSSL=false");
		ds.setUsername("root");
		ds.setPassword("123456");
		ds.setInitialSize(2);
		ds.setMaxIdle(2);
		ds.setMinIdle(2);
		
		try{
		    System.out.println(ds.getConnection().isValid(5000));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		lock=new MySQLLock(ds);
		
	}
	
	
	@Test
	public void ticketTest(){
		
		new Thread(()->sell(),"1号售票员").start();
		new Thread(()->sell(),"2号售票员").start();
		new Thread(()->sell(),"3号售票员").start();
		
		try{
		    Thread.sleep(50000);
		}catch(Exception e){}
	}
	
	
	private void sell(){
				lock.lock();
				while(count>0){		
					try{
						 System.out.println(Thread.currentThread().getName()+" 卖出第"+count+"张票");
					        count--;
					        Thread.sleep(800);
					}catch(Exception e){
						
					}finally{
						lock.unlock();
					}
			       
				}
			
	}
	
	
	
	@After
	public void destory(){
		try{
			Thread.sleep(50000);
		    ds.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
}
